package com.ruoyi.web.controller.biz;


import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.entity.TicketCode;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.service.impl.ResultMsg;
import com.ruoyi.common.service.impl.TicketCodeServiceImpl;
import com.ruoyi.utils.BarcodeGenerator;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Base64;
import java.util.List;

/**
 * <p>
 * 权益码表 控制层
 * <p>
 *
 * @author Lbb
 * @since 2024-12-06
 */
@RestController
@RequestMapping("ticket")
public class TicketCodeController extends BaseController {

    @Resource
    private TicketCodeServiceImpl ticketCodeService;

    /**
     * 查询用户权益码（券）列表
     */
    @PostMapping("/getTicketCode")
    public ResultMsg getTicketCode(@RequestParam(required = false) String companyType) throws Exception {
        if (companyType == null || companyType.trim().isEmpty()) {
            return ResultMsg.error("companyType can not be empty!!");
        }

        SysUser user = getLoginUser().getUser();
        if (user == null) {
            return ResultMsg.error("user not found, please login first（请登录）!!");
        }
        if (user.getPhonenumber() == null || user.getPhonenumber().trim().isEmpty()) {
            return ResultMsg.error("user mobile can not be empty!!");
        }
        if (user.getEmail() == null || user.getEmail().trim().isEmpty()) {
            return ResultMsg.error("user mobile can not be empty!!");
        }
        ResultMsg resultMsg=ticketCodeService.getUserTicketCodeList(companyType, user);
        List<TicketCode> ticketList = (List<TicketCode>) resultMsg.getData();

        generateBarcodesForTicketCodes(ticketList);
        return resultMsg;
    }

    public void generateBarcodesForTicketCodes(List<TicketCode> ticketList) {
        if (ticketList == null) return;

        for (TicketCode ticketCode : ticketList) {
            try {
                byte[] barcodeBytes = BarcodeGenerator.generateBarcode(ticketCode.getTicketCode(), 200, 100);
                String barcodeBase64 = Base64.getEncoder().encodeToString(barcodeBytes);
                ticketCode.setBarcodeBase64(barcodeBase64);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
